<template>
  <div class="activityExpenses-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="8">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          添加
        </el-button>
        <el-upload
          style="position: relative;bottom: 5px; margin-right: 10px"
          action="#"
          :auto-upload="false"
          multiple
          :on-change="(file) => onChecksChangeFile(file)"
          :show-file-list="false"
        >
          <el-button icon="el-icon-upload2" type="primary">导入</el-button>
        </el-upload>
        <el-button icon="el-icon-download" @click="downloadFile">
          下载模板
        </el-button>
        <el-button  type="success" @click="handleCostLog">
          费用日志
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="16">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.keyword"
              placeholder="请输入供应商名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="序号"
        width="95"
        type="index"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="项目名称"
      >
        <template #default="{ row }">
          <el-input
            disabled
            v-show="row.isEdit"
            v-model="row.activity_name"
            required
          />
          <span v-show="!row.isEdit">{{row.activity_name}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="供应商名称 / 供应商别名"
        width="240"
      >
        <template #default="{ row }">
          <div style="display: none">
            <el-select  v-show="!row.isEdit" v-model="row.supplier_id" placeholder="请选择供应商">
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.supplier_name"
                :value="supplier.id"
              />
            </el-select>
          </div>
          <el-autocomplete
            v-show="row.isEdit"
            v-model="row.supplier_name"
            :fetch-suggestions="querySearch"
            placeholder="请输入供应商"
            @select="handleSelect">
          </el-autocomplete>
          <span v-show="!row.isEdit">{{row.supplier_name}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="项目类别"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.project_category" required/>
          <span v-show="!row.isEdit">{{row.project_category}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="细项"
        width="160px"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.detail" required/>
          <span v-show="!row.isEdit">{{row.detail}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="数量"
        width="90"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.number" required/>
          <span v-show="!row.isEdit">{{row.number}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="单价"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.price" required/>
          <span v-show="!row.isEdit">{{row.price}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="subtotal"
        label="小计"
      >
        <template #default="{ row }">
          <el-input disabled="" v-show="row.isEdit" />
          <span v-show="!row.isEdit">{{row.subtotal}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="备注"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.mark" required/>
          <span v-show="!row.isEdit">{{row.mark}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="175" fixed="right">
        <template #default="{ row }">
          <div v-show="row.isEdit">
            <el-button
              type="text"
              @click="addExpenses(row)"
            >
              保存
            </el-button>
            <el-button
              type="text"
              @click="cancelExpenses(row)"
            >
              取消
            </el-button>
          </div>
          <div v-show="!row.isEdit">
            <el-button
              type="text"
              v-if="row.is_img === 2"
              @click="showUploadChecks(row.id, row)"
            >
              上传验收材料
            </el-button>
            <el-button
              v-else
              type="text"
              @click="showChecks(row)"
            >
              查看验收材料
            </el-button>
            <el-button
              type="text"
              :disabled="row.is_handler === 2"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              :disabled="row.is_handler === 2"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :page-size="queryForm.list_row"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <edit ref="edit" @fetch-data="fetchData" />

    <el-dialog
      v-if="uploadChecksVisible"
      title="验收材料"
      :visible.sync="uploadChecksVisible"
      width="800px"
      top="50px"
    >
      <el-form label-position="top">
        <el-form-item
          v-for="(type, typeIndex) in checkTypes"
          :key="type.id"
          :label="getUploadTypeLabel(type, typeIndex)"
        >
          <div class="checks-row">
            <div
              v-for="(file, fileIndex) in type.fileList"
              :key="file.uid"
              class="check-item"
              :style="{ backgroundImage: `url(${file.url})` }"
            >
              <div class="check-mask">
                <i
                  class="el-icon-delete check-delete"
                  @click="removeCheck(typeIndex, fileIndex)"
                ></i>
              </div>
            </div>
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              multiple
              accept="image/*"
              :limit="6"
              :on-exceed="onChecksExceed"
              :on-change="
                (file, fileList) => onChecksChange(fileList, typeIndex)
              "
              :file-list="type.fileList"
              :show-file-list="false"
            >
              <i class="check-add el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item
          v-if="!checkTypes.length"
          label="该项目无需提交验收材料"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadChecksVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveChecks">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!--上传反馈提示窗口-->
    <el-dialog
      v-if="uploadVisible"
      title="重名提示："
      :visible.sync="uploadVisible"
      width="800px"
    >
      <el-form label-position="top">
        <div style="width:100%;height:40px">您上传的表格中有部分供应商与系统供应商名称相近，请确认是否替换，若不替换将自动过滤该条费用。</div>
        <el-table v-loading="listLoading" :data="resList">
          <el-table-column
            align="center"
            show-overflow-tooltip
            prop="supplier_name"
            label="名称"
          />
          <el-table-column
            align="center"
            show-overflow-tooltip
            label="系统相近名称"
          >
            <template #default="{ row }">
              <el-radio-group v-model="row.radio" @change="getValue(row)">
                <el-radio :label="item.supplier_names" :key="index" v-for="(item,index) in row.supplier_name_arr">{{item.name}}</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSaves">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="查看验收材料"
      :visible.sync="checksVisible"
      width="1130px"
    >
      <div v-if="checks.length" class="checks">
        <el-image
          v-for="(check, index) in checks"
          :key="index"
          :src="checks[index]"
          :preview-src-list="checks"
          :z-index="5000"
          class="check"
          lazy
        />
      </div>
      <div v-else>没有提交验收材料</div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    doDelete,
    getExpenseChecks as getChecks,
    getList,
    updateExcel,
    doAdd,
    doEdit,
    uploadExpenseChecks as saveChecks,
    getExpenseChecks,
    getActivityexpensesadd
  } from '@/api/activityExpenses'
  import { getCheckTypes } from '@/api/activity'
  import { getList as getSupplierList } from '@/api/supplier'
  import Edit from './components/ActivityExpensesEdit'
  import { upload } from '@/api/common'

  export default {
    name: 'ActivityExpenses',
    components: { Edit },
    data() {
      return {
        radio:'',
        checkTypes: [],
        list: [],
        resList:[],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          activity_id: null,
          page: 1,
          list_row: 10,
          keyword: '',
        },
        queryForm2: {
          activity_id: '',
          supplier_id: '',
          project_category: '',
          detail: '',
          price:'',
          number:'',
          mark:''
        },
        checksVisible: false,
        uploadChecksVisible: false,
        uploadVisible: false,
        checks: [],
        suppliers: [],
        balance: 0,
        type: '',
        currentActivityId: '',
        currentRow: {},
        restaurants:[],
      }
    },
    created() {
      this.fetchData()
    },
    mounted() {
      getSupplierList({ list_row: 9999 }).then((res) => {
        this.restaurants = res.data;
      })
    },
    methods: {
      //上传-弹窗-确认
      handleSaves(){
        this.resList.forEach(item => {
          if(item.supplier_id){
            getActivityexpensesadd(item).then(res =>{
              this.uploadVisible = false;
              this.fetchData();
            })
          }
        })
      },
      //上传-弹窗-单选框
      getValue(row){
        console.log(456,row.supplier_name)
        console.log(789,this.resList)
        this.resList.forEach(item => {
          if(item.supplier_name === row.supplier_name){
            let arr= item.radio.split("-")
            this.$set(item, 'supplier_id', arr[1])
          }
        })
        console.log(110,this.resList)
      },
      handleSaveChecks() {
        if (!this.validateChecks()) return
        const types = this.checkTypes
        let typeImages
        types.forEach((type) => {
          const files = type.fileList
          typeImages = files.map((file) => file.url).join(',')
        })
        saveChecks({
          id: this.currentActivityId,
          check_img: typeImages,
        }).then((res) => {
          this.uploadChecksVisible = false
          this.fetchData()
          this.$baseMessage(res, 'success')
        })
      },
      onChecksExceed() {
        this.$baseMessage('最多只能上传 6 张图片哦', 'warning')
      },
      onChecksChange(fileList, index) {
        // 注: fileList 包含全部图片
        const type = this.checkTypes[index]
        // 处理待上传图片
        const formData = new FormData()
        fileList
          .filter((file) => file.raw)
          .forEach((file) => formData.append('file[]', file.raw))
        // 上传图片
        upload(formData).then((res) => {
          // 上传后处理
          const urls = res.url
          type.fileList = [
            ...fileList.filter((file) => !file.raw),
            ...urls.map((url) => ({ url })),
          ]
          this.$set(this.checkTypes, index, type)
        })
      },
      validateChecks() {
        const types = this.checkTypes
        for (const type of types) {
          const files = type.fileList
          for (const file of files) {
            if (file.url.startsWith('blob:')) {
              this.$baseMessage('图片上传中，请重试', 'error')
              return false
            }
          }
        }
        return true
      },
      removeCheck(typeIndex, fileIndex) {
        this.checkTypes[typeIndex].fileList.splice(fileIndex, 1)
        this.$forceUpdate()
      },
      getUploadTypeLabel(type, index) {
        let label = type.project_category
        const num = type.fileList.length
        // label += ` ${index ? `(${num}/6)` : num}`
        label += ` (${num}/6)`
        return label
      },
      cancelExpenses(row) {
        if (this.type == 'add') {
          this.list.splice(0, 1)
        } else {
          row.isEdit = false
          this.list = this.list.concat([])
        }
        this.type = ''
      },
      async addExpenses(row) {
        console.log(4321,row)
        let msg
        this.$set(row, 'supplier_id', '')
        row.activity_id = this.$route.query.activity_id
        if (this.type === 'add') {
          this.restaurants.forEach(item =>{
            if(item.supplier_name === row.supplier_name){
              row.supplier_id = item.id
            }
          })
          msg = await doAdd(row)
        } else {
          this.restaurants.forEach(item =>{
            if(item.supplier_name === row.supplier_name){
              row.supplier_id = item.id
            }
          })
          msg = await doEdit(row)
        }
        this.type = ''
        this.fetchData()
        this.$baseMessage(msg, 'success')
      },
      onChecksChangeFile(file, index) {
        // 处理待上传图片
        const formData = new FormData()
        formData.append('file', file.raw)
        // 上传图片
        updateExcel(formData, this.$route.query.activity_id).then(res => {
          console.log(4444,res)
          if(res && res.length>0){
            //上传弹窗信息
            this.uploadVisible = true;
            let resData = res;
            resData.forEach(item => {
              this.$set(item,'radio','')
              item.supplier_name_arr.forEach(item2 =>{
                item2.supplier_names = item.supplier_name + '-' + item2.supplier_id
              })
            })
            this.resList = resData;
            console.log(666,this.resList)
          }
          this.fetchData()
        })
        console.log(5555)
      },
      downloadFile() {
        location.href = 'http://sc.dtc.zone/activity_temp.xlsx'
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        console.log(44444,row)
        if(this.type != '') return
        getSupplierList({ list_row: 9999 }).then((res) => {
          console.log(111111111,this.list)
          this.suppliers = res.data;
          if (row.id) {
            console.log(2222222)
            this.type = 'edit'
            row.isEdit = true
          } else {
            console.log(3333333)
            this.type = 'add'
            this.list.unshift({ activity_name: this.$route.query.activity_name })
            this.list[0].isEdit = true
          }
        })
      },
      querySearch(queryString, cb) {
        console.log(231,this.restaurants)
        if (this.restaurants && this.restaurants.length>0){
          this.restaurants.forEach(item =>{
            this.$set(item, 'value', item.supplier_name)
          })
        }
        let restaurants = this.restaurants;
        let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        console.log(2222,queryString)
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
        };
      },
      handleSelect(item) {
        console.log(222,item);
      },
      handleCostLog(row) {
        console.log(row)

        const activity_id = this.$route.query.activity_id;
        const activity_name = this.$route.query.activity_name;
        this.$router.push({
          name: 'ActivityCostLog',
          query: { activity_id, activity_name },
        })
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ activity_expenses_id: row.id })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.list_row = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.page = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        this.queryForm.activity_id = +this.$route.query.activity_id
        const { data, total, balance } = await getList(this.queryForm)
        this.balance = balance
        this.list = data
        this.total = total
        this.listLoading = false
      },
      inDev() {
        this.$message('开发中')
      },
      showUploadChecks(id, row) {
        this.currentActivityId = id
        this.currentRow = row
        const types = [{
          project_category: '上传材料',
          fileList: []
          // fileList: type.check_img.map((img) => ({
          //   uid: Math.random(),
          //   url: img,
          // })),
        }]
        // types.unshift({ id: 0, project_category: '未分配', fileList: [] })
        this.checkTypes = types
        this.uploadChecksVisible = true
      },
      showChecks(row) {
        getExpenseChecks({ id: row.id }).then((res) => {
          this.checks = res
          this.checksVisible = true
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
el-dialog{
  min-height: 500px !important; overflow-y: auto !important;
}
  .table-expand {
    font-size: 0;
    ::v-deep {
      label {
        width: 120px;
        color: #99a9bf;
      }
      .el-form-item {
        width: 50%;
        margin-right: 0;
        margin-bottom: 0;
      }
    }
  }

  ::v-deep {
    .el-table__expanded-cell {
      padding: 20px 50px !important;
    }
  }

  .status-rejected {
    color: #f56c6c;
    cursor: help;
    border-bottom: 1px dashed #dcdfe6;
  }

  ::v-deep .dialog-orders {
    width: 80%;

    @media (min-width: 1440px) {
      width: 60%;
    }
  }

  .checks {
    display: flex;
    flex-wrap: wrap;
    margin-right: -10px;
    margin-bottom: -10px;
  }

  .check {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .invoice-img {
    display: block;
    margin-bottom: 18px;
  }

  .search-input {
    width: 250px;
  }

  .checks-row {
    display: flex;
    align-items: center;
  }

  .check-item {
    position: relative;
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    background-position: center;
    background-size: cover;
    border: 1px solid #c0ccda;
    border-radius: 7px;
  }

  .check-mask {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: 0.3s;
  }

  .check-item:hover .check-mask {
    opacity: 1;
  }

  .check-delete {
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 20px;
    color: #fff;
    cursor: pointer;
    transform: translate(-50%, -50%);
  }

  ::v-deep .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 100px;
  }

  .check-add {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>
